const Ajax = {
  get: function(url, fn) {
    // XMLHttpRequest对象用于在后台与服务器交换数据
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, false);
    xhr.onreadystatechange = function() {
      // readyState == 4说明请求已完成
      if (xhr.readyState == 4) {
        if (xhr.status == 200 || xhr.status == 304) {
          fn.call(xhr.responseText);
        }
      }
    };
    xhr.send();
  },

  post: function({
    url, data, success, headers = ''
  }) {
    let xhr = new XMLHttpRequest();
    xhr.open('POST', url, false);
    // 添加http头，发送信息至服务器时内容编码类型
    if (headers) {
      let headerKey = Object.keys(headers);
      headerKey.forEach(key => {
        xhr.setRequestHeader(key, headers[key]);
      });
    }
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        if (xhr.status == 200 || xhr.status == 304) {
          // console.log(xhr.responseText);
          success(xhr.response);
        }
      }
    };
    xhr.send(data);
  },
  async getPromise({ url }) {
    return new Promise((resolve, reject) => {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', url, false);
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          if (xhr.status == 200 || xhr.status == 304) {
            resolve(xhr.responseText);
          }
        }
      };
      xhr.send();
    });
  },
  async postPromise({ url, data = { }, headers = {} }) {
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.open('POST', url, false);
      // 添加http头，发送信息至服务器时内容编码类型
      if (headers) {
        let headerKey = Object.keys(headers);
        headerKey.forEach(key => {
          xhr.setRequestHeader(key, headers[key]);
        });
      }
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          if (xhr.status == 200 || xhr.status == 304) {
            // console.log(xhr.responseText);
            resolve(xhr.response);
          }
        }
      };
      xhr.send(data);
    });
  }
};

export {
  Ajax
};
